<?php
namespace App\Services;

use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Illuminate\Support\Facades\Log;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
use Swoole\Coroutine as co;
use App\Jobs\TestTask;


use App\Events\MessageReceived;
use App\User;
use Hhxsv5\LaravelS\Swoole\Task\Event; 

class WebSocketService implements WebSocketHandlerInterface
{
    public function __construct()
    {

    }
    // public function onWorkerStart(Server $server,$worker_id){
    
    // 	Log::channel('daily')->info('1');

    // }

    // 连接建立时触发
    public function onOpen(Server $server, Request $request)
    { 
    	
    	
    	Log::channel('daily')->info('2');
        //print_r($server->connections);
        // 在触发 WebSocket 连接建立事件之前，Laravel 应用初始化的生命周期已经结束，你可以在这里获取 Laravel 请求和会话数据
        // 调用 push 方法向客户端推送数据，fd 是客户端连接标识字段
       
        //Log::info('WebSocket');
        // echo 2;
        //$server->push($request->fd, 'Welcome to WebSocket Server built on LaravelS');
    }

    // 收到消息时触发
    public function onMessage(Server $server, Frame $frame)
    {
    	// $frame->fd 是客户端 id，$frame->data 是客户端发送的数据
        Log::info("从 {$frame->fd} 接收到的数据: {$frame->data}");
        $message = json_decode($frame->data);
        // 基于 Token 的用户认证校验
        if (empty($message->token) || !($user = User::where('api_token', $message->token)->first())) {
            Log::warning("用户" . $message->name . "已经离线，不能发送消息");
            $server->push($frame->fd, "离线用户不能发送消息");  // 告知用户离线状态不能发送消息
        } else {

            // 触发消息接收事件
            $event = new MessageReceived($message, $user->id);
            Event::fire($event);
            unset($message->token);  // 从消息中去掉当前用户令牌字段
            foreach ($server->connections as $fd) {
                if (!$server->isEstablished($fd)) {
                    // 如果连接不可用则忽略
                    continue;
                }
                $server->push($fd, json_encode($message)); // 服务端通过 push 方法向所有连接的客户端发送数据
            }
        }


        //异步队列任务  
        // $task = new TestTask('heal ceshi');
        // $success = \Hhxsv5\LaravelS\Swoole\Task\Task::deliver($task); 
        // print_r($success); 

        

    
        
        //$chan = new co\channel(1);

        // go(function() use($chan){
        //      var_dump(time());

        //     for ($i=0; $i <2 ; $i++) { 
        //         // co::sleep(3.0);
        //         $chan->push(['rand' => rand(1000, 9999), 'index' => $i]);
        //         echo "$i\n";
        //         # code...
        //     }
        
        // });

        // $results = [];
        //     for ($i = 0; $i < 3; $i++) {
        //         $results[] = $chan->pop();
        //         Log::channel('daily')->info($chan->pop());
        //     }

        // print_r($results);
    }

    // 关闭连接时触发
    public function onClose(Server $server, $fd, $reactorId)
    {
    	//Log::channel('daily')->info('4');
    	
    	
        //Log::info('WebSocket 连接关闭');
    }
    
}


?>